import { existplayer,Read_player,Write_player,Add_player,__PATH,get_player_img,Write_json,Read_json
    ,alluser,Go,Go2,getPlayerAction,isNotNull,getGuojiaIndex,getGuojia,hasPassedOneDay,getfuben } from "../game/sanguo.js";
import data from '../../model/sanguoData.js'
import fs from 'fs';
let type=["剑兵","骑兵","长矛兵","弓兵"]
let type2=["重骑兵",
"骑射兵",
"火弓兵",
"弩弓兵",
"神射手",
"重剑兵",
"轻剑兵",
"神剑兵",
"重矛兵",
"神矛兵"]
export class zhandou extends plugin {
    constructor() {
      super({
        /** 功能名称 */
        name: '三国|战斗模块',
        /** 功能描述 */
        dsc: '战斗模块',
        event: 'message',
        /** 优先级，数字越小等级越高 */
        priority: 600,
        rule: [
          {
            reg: /^(#|\/)转换兵种.*$/,
            fnc: 'zhuan',
          },
          {
            reg: /^(#|\/)查看副本$/,
            fnc: 'fuben',
          },
          {
            reg: /^(#|\/)攻打副本.*$/,
            fnc: 'gofuben',
          },
          {
            reg: /^(#|\/)创建队伍.*$/,
            fnc: 'jian',
          },
          {
            reg: /^(#|\/)添加普通兵种.*$/,
            fnc: 'bingz',
          },
          {
            reg: /^(#|\/)减少普通兵种.*$/,
            fnc: 'jianbingz',
          },
          {
            reg: /^(#|\/)添加特殊兵种.*$/,
            fnc: 'bingt',
          },
          {
            reg: /^(#|\/)减少特殊兵种.*$/,
            fnc: 'jianbingt',
          },
          {
            reg: /^(#|\/)添加队伍兵.*$/,
            fnc: 'bing',
          },
          {
            reg: /^(#|\/)减少队伍兵.*$/,
            fnc: 'jianbing',
          },
          {
            reg: /^(#|\/)添加武将.*$/,
            fnc: 'wujiang',
          },
          {
            reg: /^(#|\/)减少武将.*$/,
            fnc: 'jianwujiang',
          },
          {
            reg: /^(#|\/)查看队伍状态.*$/,
            fnc: 'check',
          },
          {
            reg: /^(#|\/)测试结束状态.*$/,
            fnc: 'stop',
          },
          {
            reg: /^(#|\/)查看普通兵种.*$/,
            fnc: 'check1',
          },
          {
            reg: /^(#|\/)查看特殊兵种.*$/,
            fnc: 'check2',
          },
        ]
      });
    }
    async check1(e){
       let message = type.join(", "); // 使用逗号和空格连接数组元素
       return e.reply(message)
    }
    async check2(e){
        let message = type2.join(", "); // 使用逗号和空格连接数组元素
        return e.reply(message)
    }
    async bingt(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq);
        if (!exist) {
            e.reply(`没有存档`);
            return false;
        }
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/添加特殊兵种", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#添加特殊兵种", '');
        }
        qian = qian.trim();
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的数量
        let zong = code[1].trim(); // 兵的种类
        let num = code[2].trim(); // 队伍编号
        console.log(bing);
        console.log(zong);
        console.log(num);
        num=parseInt(num)
        bing=parseInt(bing)
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        }
       
        console.log( Object.values(type2).filter(兵种 => 兵种 !== zong));
        const 兵种列表 = Object.values(type2);
        if (!兵种列表.includes(zong)) {
            e.reply(`没有此类兵种`);
            return;
        }
        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        if (bing>guojia.特殊兵种[zong]) {
            return e.reply(`${zong}的人数不够`);
        }
        
        // 将兵的数量从字符串类型转换为数字类型
        team.兵种[zong] += parseInt(bing);
        guojia.特殊兵种[zong]-=parseInt(bing)
        e.reply(`添加成功，目前有${team.兵种[zong]}个${zong}`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async jianbingt(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq);
        if (!exist) {
            e.reply(`没有存档`);
            return false;
        }
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/减少特殊兵种", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#减少特殊兵种", '');
        }
        qian = qian.trim();
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的数量
        let zong = code[1].trim(); // 兵的数量
        let num = code[2].trim(); // 队伍编号
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        }
        const 兵种列表 = Object.values(type2);
        if (!兵种列表.includes(zong)) {
            e.reply(`没有此类兵种`);
            return;
        }        
         const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        if (bing>team.兵种[zong]) {
            return e.reply(`队伍中${zhong}的人数不够`);
        }
        // 将兵的数量从字符串类型转换为数字类型
        guojia.特殊兵种[zong]+=parseInt(bing);
        team.兵种[zong] -= parseInt(bing);
        e.reply(`减少成功，目前有${team.兵种[zong]}个兵`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async bingz(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq);
        if (!exist) {
            e.reply(`没有存档`);
            return false;
        }
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/添加普通兵种", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#添加普通兵种", '');
        }
        qian = qian.trim();
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的数量
        let zong = code[1].trim(); // 兵的种类
        let num = code[2].trim(); // 队伍编号
        console.log(bing);
        console.log(zong);
        console.log(num);
        num=parseInt(num)
        bing=parseInt(bing)
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        }
        const 兵种列表 = Object.values(type);
        if (!兵种列表.includes(zong)) {
            e.reply(`没有此类兵种`);
            return;
        }

        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        if (bing>guojia.普通兵种[zong]) {
            return e.reply(`${zong}的人数不够`);
        }
        
        // 将兵的数量从字符串类型转换为数字类型
        team.兵种[zong] += parseInt(bing);
        guojia.普通兵种[zong]-=parseInt(bing)
        e.reply(`添加成功，目前有${team.兵种[zong]}个${zong}`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async jianbingz(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq);
        if (!exist) {
            e.reply(`没有存档`);
            return false;
        }
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/减少普通兵种", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#减少队伍兵", '');
        }
        qian = qian.trim();
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的数量
        let zong = code[1].trim(); // 兵的数量
        let num = code[2].trim(); // 队伍编号
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        }
        const 兵种列表 = Object.values(type);
        if (!兵种列表.includes(zong)) {
            e.reply(`没有此类兵种`);
            return;
        }
        
         const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        if (bing>team.兵种[zong]) {
            return e.reply(`队伍中${zong}的人数不够`);
        }
        // 将兵的数量从字符串类型转换为数字类型
        guojia.普通兵种[zong]+=parseInt(bing);
        team.兵种[zong] -= parseInt(bing);
        e.reply(`减少成功，目前有${team.兵种[zong]}个兵`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async zhuan(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq)
        if (!exist) {
            e.reply(`没有存档`)
            return false;
        }
        let player =await Read_player(1,usr_qq)
        let guojia = await getGuojia(player.国家)
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/转换兵种", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#转换兵种", '');
        }
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的种类
        let num = code[1].trim(); // 兵的数量
        num=parseInt(num)
        if (guojia.兵<num) {
            e.reply(`没有这么多兵`)
        }
        const 不等于兵种 = type.find(兵种 => 兵种 === bing);
        if (!不等于兵种) {
            e.reply(`没有此类兵种`)
            return;
        }
        if (player.金钱 < num*10000) {
            e.reply(`没有${num*10000}的金钱为兵转换兵种`)
            return;
        }
        guojia.普通兵种[bing]+=num
        guojia.兵-=num
        e.reply(`转换成功`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async stop(e){
         const usr_qq = e.user_id;
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/测试结束状态", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#测试结束状态", '');
        }
        qian = qian.trim();
        await redis.del(`sanguo:${qian}:${usr_qq}:action`);
        return e.reply(`结束成功`)
    }
    async check(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq)
        if (!exist) {
            e.reply(`没有存档`)
            return false;
        }
        let player =await Read_player(1,usr_qq)
        let guojia = await getGuojia(player.国家)
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/查看队伍状态", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#查看队伍状态", '');
        }
        qian = qian.trim();
        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(qian));
        if (!await Go2(e,qian)) {
            return;
        }
        e.reply(`空闲中`)
        return;
    }
    async jian(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq)
        if (!exist) {
            e.reply(`没有存档`)
            return false;
        }
        let player =await Read_player(1,usr_qq)
        let guojia = await getGuojia(player.国家)
        let num = guojia.队伍.length +1
        let duiwu={
            编号:num,
            兵:0,
            武将:[],
            状态:"无",
            兵种:{
            剑兵:0,
            骑兵:0,
            长矛兵:0,
            弓兵:0,
            重骑兵:0,
            骑射兵:0,
            火弓兵:0,
            弩弓兵:0,
            神射手:0,
            重剑兵:0,
            轻剑兵:0,
            神剑兵:0,
            重矛兵:0,
            神矛兵:0
        }
        }
        guojia.队伍.push(duiwu)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        e.reply(`创建队伍${num}成功`)
        return;
    }
    async bing(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq);
        if (!exist) {
            e.reply(`没有存档`);
            return false;
        }
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/添加队伍兵", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#添加队伍兵", '');
        }
        qian = qian.trim();
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的数量
        let num = code[1].trim(); // 队伍编号
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        }
        let num2 = 0;
        for (let i = 0; i < guojia.队伍.length; i++) {
        num2 += guojia.队伍[i].兵;
        if (guojia.兵 - num2 < bing) {
            e.reply(`兵不足`);
            return;
        }
        }

      
        // let team;
        // for (let i = 0; i < guojia['队伍'].length; i++) {
        //  if (parseInt(guojia['队伍'][i][`编号`]) === parseInt(num)) {
        //     console.log(i);
        //     console.log(guojia['队伍'][i]);
        //     team = guojia['队伍'][i];
        //     break;
        // }
        // }
        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        // 将兵的数量从字符串类型转换为数字类型
        console.log(team.兵);
        console.log(bing);
        team.兵 += parseInt(bing);
        guojia.兵-=parseInt(bing);

        // // 在使用之前先移除原有的队伍数据
        // guojia.队伍 = guojia.队伍.filter(item => item.编号 !== num);

        // // 将修改后的队伍数据添加回guojia对象
        // guojia.队伍.push(team);
        e.reply(`添加成功，目前有${team.兵}个兵`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async jianbing(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq);
        if (!exist) {
            e.reply(`没有存档`);
            return false;
        }
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
            qian = e.msg.replace("/减少队伍兵", '');
        } else if (e.msg.includes("#")) {
            qian = e.msg.replace("#减少队伍兵", '');
        }
        qian = qian.trim();
        let code = qian.split('*');
        let bing = code[0].trim(); // 兵的数量
        let num = code[1].trim(); // 队伍编号
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        }

      
       
        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        // 将兵的数量从字符串类型转换为数字类型
        console.log(team.兵);
        console.log(bing);
        team.兵 -= parseInt(bing);
        guojia.兵+=parseInt(bing);
        e.reply(`添加成功，目前有${team.兵}个兵`)
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async hasTeamWithNumber(teams, number) {
        return teams.some(team => parseInt(team.编号) === parseInt(number));
    }
    async wujiang(e){
        const usr_qq = e.user_id;
        const exist = await existplayer(1, usr_qq);
        if (!exist) {
          e.reply(`没有存档`);
          return false;
        }
        
        const player = await Read_player(1, usr_qq);
        const guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
          qian = e.msg.replace("/添加武将", '');
        } else if (e.msg.includes("#")) {
          qian = e.msg.replace("#添加武将", '');
        }
        qian = qian.trim();
        const code = qian.split('*');
        const bing = code[0].trim(); // 武将名称
        let shu =code[1].trim(); // 武将数量
        const num = code[2].trim(); // 队伍编号
        shu = parseInt(shu)
        console.log(bing);
        console.log(shu);
        console.log(num);
        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
          e.reply(`没有编号为${num}的队伍`);
          return;
        }
        
        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        const team2 = guojia.武将.find(team => team.name === bing);
        if (!await isNotNull(team2)) {
          e.reply(`没有这个武将`);
          return;
        }
        
        let num3 = 0;
        
        for (let i = 0; i < guojia.队伍.length; i++) {
            let hasProperty = guojia.队伍[i].武将.some(item => item.name === bing);
            if (hasProperty) {
                const team3 = guojia.队伍[i].武将.find(team => team.name === bing);
                num3 += team3.数量;
            }       
    }
            if (team2.数量 <= num3 + shu) {
              e.reply(`武将不足（这里的不足指的是武将在别的队伍了）`);
              return;
          }
        
        const hasSameName = team && team.武将.some(wujiang => wujiang.name === bing);
        if (hasSameName) {
          team.武将.forEach(wujiang => {
            if (wujiang.name === bing) {
              wujiang.数量 += shu;
            }
          });
        } else {
          const wujiang = {
            name: team2.name,
            武力值: team2.武力值,
            数量: shu
          };
          team.武将.push(wujiang);
        }
        team2.数量 -=shu;
        e.reply(`增加${bing}成功`);
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async jianwujiang(e){
        const usr_qq = e.user_id;
        const exist = await existplayer(1, usr_qq);
        if (!exist) {
        e.reply(`没有存档`);
        return false;
        }

        const player = await Read_player(1, usr_qq);
        const guojia = await getGuojia(player.国家);
        let qian;
        if (e.msg.includes("/")) {
        qian = e.msg.replace("/减少武将", '');
        } else if (e.msg.includes("#")) {
        qian = e.msg.replace("#减少武将", '');
        }
        qian = qian.trim();
        const code = qian.split('*');
        const bing = code[0].trim(); // 武将名称
        let shu = parseInt(code[1].trim()); // 武将数量
        const num = code[2].trim(); // 队伍编号

        if (!this.hasTeamWithNumber(guojia.队伍, num)) {
        e.reply(`没有编号为${num}的队伍`);
        return;
        }

        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        const team2 = team.武将.find(item => item.name === bing);
        if (!isNotNull(team2)) {
        e.reply(`没有这个武将`);
        return;
        }
        console.log(team2.数量);
        console.log(shu);
        if (team2.数量 < shu) {
        e.reply(`没有这么多武将`);
        return;
        }

        team2.数量 -= shu;
        if (team2.数量 === 0) {
        const index = team.武将.indexOf(team2);
        team.武将.splice(index, 1);
        }
        team2.数量+= shu

        e.reply(`减少${bing}成功`);
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;

    }
    async fuben(e){

        let weizhi = await data.fuben_list
        await getfuben(e, weizhi)
        return;
    }
    async gofuben(e){
        const usr_qq = e.user_id;
        let exist = await existplayer(1, usr_qq)
        if (!exist) {
            e.reply(`没有存档`)
            return false;
        }
        const player = await Read_player(1, usr_qq);
        const guojia = await getGuojia(player.国家);
       
        let didian ;
        if(e.msg.includes("/")){
            didian = e.msg.replace("/攻打副本", '');
        }else if(e.msg.includes("#")){
            didian = e.msg.replace("#攻打副本", '');
        }
        didian = didian.trim()
        let code = didian.split('*');
        let bing = code[0].trim(); // 副本名称
        let num = code[1].trim(); // 队伍编号
        let weizhi = await data.fuben_list.find(item => item.name == bing);
        if (!isNotNull(weizhi)) {
            e.reply(`没有${didian}副本`)
            return false
        }
         if (!this.hasTeamWithNumber(guojia.队伍, num)) {
            e.reply(`没有编号为${num}的队伍`);
            return;
        } 
        const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(num));
        if (team.状态 != "无") {
            e.reply(`这个队伍正在${team.状态}`)
            return;
        }
        if (team.兵 === 0) {
            e.reply(`没有兵打啥副本`)
            return;
        }
        let currentTimeStamp = new Date().getTime()
        team.状态 = "攻打副本"
        let time = 30
        let arr={
            action:"攻打副本",
            fuben:bing,
            start_time:currentTimeStamp,
            wujiang:team.武将,
            time:time,
            bing:team.兵,
            team:team ,
            player:player,
            num:num
        }
        await redis.set(`sanguo:${num}:${usr_qq}:action`,
        JSON.stringify(arr));
        e.reply('开始攻打' + bing + ',' + time + '分钟后归来!')
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
    }
    async dao(e){
        const usr_qq = e.user_id;
        let player =await Read_player(1,usr_qq)
        let guojia = await getGuojia(player.国家)
        const contextValue = this.getContext('dao');
        if (guojia.兵 < contextValue) {
            e.reply(`你没有这么多兵`)
            return;
        }
        people = contextValue
        this.setContext('dao2');
        await e.reply("请输入你想要派出武将（格式武将名*数量如不添加请输入取消）", false, {
          at: true
        });
    }
    async dao2(e) {
        const usr_qq = e.user_id;
        let player = await Read_player(1, usr_qq);
        let guojia = await getGuojia(player.国家);
        const newMsg = this.e.msg;
        const regex = /(.*)\*(.*)|取消/;
        const matches = regex.exec(newMsg);
        if (matches == "取消") {
            let time = 30
            let arr={
                action:"攻打副本",
                fuben:fuben,
                start_time:currentTimeStamp,
                wujiang:people2,
                time:time,
                bing:people
            }
            await redis.set(`sanguo:player:${usr_qq}:action`,
            JSON.stringify(arr));
            e.reply('开始攻打' + fuben + ',' + time + '分钟后归来!')
            return;
        }
        if(matches != "取消"){
        if (matches) {
            const wujiang = matches[1]; // 获取星号左边的值（武将名）
            const quantity = matches[2]; // 获取星号右边的值（数量）
            let wujiangdata = await data.wujiang_list.find(item => item.name == wujiang);
            let wujiangnum = await guojia.武将.find(item => item.name == wujiang);
            if (!isNotNull(wujiangdata)) {
                e.reply(`没有${wujiang}这个武将`);
                return;
            } else if (wujiangnum.数量 < quantity) {
                e.reply(`${wujiang}不足${quantity}个`);
                return;
            }
            let str = {
                name: wujiang,
                武力值: wujiangnum.武力值,
                数量: quantity
            };
            people2.push(str);
            this.setContext('dao3');
            await e.reply("是否继续添加武将（回答是或否）", false, {
                at: true
            });
            return;
        }
    }

    }
    
     async dao3(e){
      let usr_qq =e.user_id
      let contextValue = this.getContext('dao2');
      let currentTimeStamp = new Date().getTime()
        if (contextValue === "是") {
            this.setContext('dao2');
            await e.reply("请输入你想要派出武将（格式武将名*数量）", false, {
            at: true
            });
            return;
        }else{
        if (contextValue === "否") {
            let time = 30
            let arr={
                action:"攻打副本",
                fuben:fuben,
                start_time:currentTimeStamp,
                wujiang:people2,
                time:time,
                bing:people
            }
            await redis.set(`sanguo::${usr_qq}:action`,
            JSON.stringify(arr));
            e.reply('开始攻打' + fuben + ',' + time + '分钟后归来!')
            return;
            }
        }
        return;
    }
}